/**
 * Created by hetanhong on 2014/9/1.
 */
(function () {
    var dongtai = function (config) {
        this._config = config;
        this._type = this.getConfig("type"); //公文类别
        this._typeReal = this.getConfig("typeReal");//公文类别
        this._businessType = this.getConfig("businessType");
        this._title = this.getConfig("title");
        this._send = this.getConfig("send") || false;
        this._next = null;// 操作按钮布局
        this._id = this.getConfig("id"); //公文id
        this._taskName = this.getConfig("taskName"); //流程名称
        this._taskId = this.getConfig("taskId"); //待办id
        this._div = this.getConfig("div");
        this._buttonFlag = this.getConfig("buttonFlag") || "";// 按钮是否从服务器读取
        this.width = window.innerWidth || 320;
        this.height = window.innerHeight || 480;
        this.requestUrl = ""; //按钮操作交互地址
        this._screenindex = this.getConfig("screenindex"); //上一步页面来源 1 待办 2 通知 3 应用 4 账户

    };
    if (typeof (Clickmed) === "undefined") {
        Clickmed = {};
    }
    Clickmed.dongtai = dongtai;
    // 动态数据请求，初始化
    dongtai.prototype.init = function () {
        var me = this;
        console.log(this);
        getDicts(function (dat) {
            me.Dicts = dat;
            console.log(dat);
            var url = serverURL + "cmcp/dynawork/getDynaWorkIndex";
            var self = {
                id: me._id
            };
            window.plugins.getIntent.show(["OA", "正在获取数据"]);
            //   向后台请求数据
            PostCP(url, self, function (dat) {
                me.dat = dat;
                if (!me._buttonFlag) {
                    var url = serverURL + "cmcp/phone/getApprovalUserInfo";
                    var self = {
                        taskId: me._config.taskId
                    };
                    PostCP(url, self, function (button) {
                        me.button = button;
                        console.log(button);
                        me.draw();
                        var url = serverURL + "cmcp/phone/doGetLanguages";
                        PostCP(url, null, function (dat) {
                            me.languages = dat;
                        });
                    }, function () {
                        console.log("err");
                    });
                }
                else {
                    me.draw();
                }
                return;
            }, function () {
                Prompt("获取数据失败", 1000);
            });
        })


    };
    // 动态 布局展示
    dongtai.prototype.draw = function () {
        var me = this;
        var render = this._config.render || d3.select("body");
        var d1 = this._config.body || d3.select("body");
        var width = this.width;
        var scrol = d1.append("div").classed("scrol", true).style({
            width: this.width + "px",
            height: this.height + "px",
            position: "absolute",
            background: "#fff",
            left: "0px",
            "z-index": 99,
            top: "0px"
        }).attr("id", "scrol");

        var warp = scrol.append("div").classed("dt_warp", true).style({
            position: "relative"
        });
        var datong_header = warp.append("div").classed("datong_header", true);

        var go_back = datong_header.append("div").classed("go_back", true);
        go_back.html("<i><img src =../../common/page/images/go_back_ico.png width =16 height=auto></i>返回");
        go_back.on(touch_s, function () {
            $(this).css("background-color", "#005ebf");
        });
        go_back.on(touch_e, function () {
            $(this).css("background-color", "");

            d1.selectAll("#scrol").remove();
            setTimeout(function () {
                Android.back = TempFunction.back;
            }, Transiacion);

        });
        // 返回操作
        function back1() {

            d1.selectAll("#scrol").remove();
            Android.back = TempFunction.back;
        }

        // Android返回键动作
        Android.back = TempFunction.back1 = back1;
        datong_header.append("h1").html(me._taskName);
        me.Redraw();

    };
    // 动态数据展示
    dongtai.prototype.Redraw = function () {
        var me = this;
        console.log(me);
        var warp = d3.select("#scrol .dt_warp");
        var title = me.dat["title"] || "工作动态";
        var subitems = me.dat["subitems"] || null;
        console.log(subitems);
        var dist = 44;
        if (!me._buttonFlag) {
            dist = 100;
            me.showButton();
        }
        if (me._send) {
            dist = 100;
            me.sendButton();
        }
        var scrol_ = warp.append("div").classed("scrol_", true).style({
            width: "100%",
            height: height - dist + "px",
            postion: "relative",
            overflow: "hidden"
        }).attr("id", "scrol_");
        var datong_con = scrol_.append("div").classed("datong_con datong_con_re", true);
        datong_con.append("div").classed("tongzhiTitle", true).style({
            "text-align": "center"
        }).html(title).classed("title", true);
        var datong_con = datong_con.append("div").classed("phone_cotent", true);
        for (var name in subitems) {

            if (!subitems[name]) {
                continue;

            }
            console.log(name);
            var report_title = datong_con.append("div").classed("report_title", true).html(me.turnName(name));
            for (var con in subitems[name]) {
                if (!subitems[name][con] || subitems[name][con] == {}) {
                    continue;
                }
                var ul = datong_con.append("ul");
                var li = ul.append("li").classed("b_btm", true).style({
                    padding: "5px 0px"
                });
                var dl = li.append("dl");

                dl.append("dd")//.html(" <b style='border-bottom:2px solid #2875c3'>事项内容 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</b> </br>");
                dl.select("dd").append("div").html(subitems[name][con]["content"].replace(/\n/g, "<br>").replace(/\s/g, "&nbsp")).style({
                    "font-size": "15px",
                    "margin-top": "3px"
                });
            }


        }
        /* 流程跟踪
         */
        if ( !me._send) {
            var report_title = d3.select(".datong_con_re").append("div").classed("report_title", true).html("流程跟踪");
            report_title.style({
                background: "#f2f2f0",
                color: "#2345e6",
                "border-radius": "10px",
                "margin": "0% 2% 2% 2%"
            })
            report_title.on("click", function () {
                if (Flag)
                    return;
                Flag = true;
                me.openNew();

                setTimeout(function () {
                    Flag = false;
                }, 500);
            });
        }

        Yscroll = new iScroll("scrol_", {hScrollbar: false, vScrollbar: false});
    };
    //待提交动态，发送
    dongtai.prototype.sendButton = function () {

        var me = this;
        var warp = d3.select("#scrol .dt_warp");
        var button = warp.append("div").classed("tj_button2", true).classed("qb_btn_bg", true);
        var tj_button = button.append("p").style({
            "text-align": "center"
        });
        var input = tj_button.append("input").classed("other", true)

            .attr("type", "button")

            .attr("value", "发   送").style({
                width: "36.1%"

            });
        input.on("click", function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            var url = serverURL + "cmcp/noticenter/addLeadersTodo";
            var self = {
                id: me._id,
                title: me._title
            };
            PostCP(url, self, function (dat) {
                if (!dat) {
                    Prompt("发送失败");
                    return;
                }
                if (dat) {
                    Prompt("发送成功");
                    d3.selectAll("#scrol").remove();
                    setTimeout(function () {
                        me._div.remove();
                        myscroll.refresh();
                    }, Transiacion);
                    Android.back = TempFunction.back;
                }
            }, function () {
                Prompt("发送失败", 1000);
            });

        });

    };
    // 动态 操作按钮展示
    dongtai.prototype.showButton = function () {
        var me = this;
        var warp = d3.select("#scrol .dt_warp");
        var button = warp.append("div").classed("tj_button2", true).classed("qb_btn_bg", true);
        var tj_button = button.append("p").style({
            "text-align": "center"
        });


        var buttons = me.button["button"];
        console.log(buttons);
        for (var name in buttons) {
            var input = tj_button.append("input").classed("other", true)
                .attr("action", buttons[name]["action"] || "")
                .attr("type", "button")
                .attr("mark", buttons[name]["mark"])
                .attr("requestUrl", buttons[name]["requestUrl"])
                .attr("value", buttons[name]["name"]).style({
                    width: "26.1%"

                });
            $(input.node()).data("userInfo", buttons[name]["userInfo"] || "");
        }
        $(".other").on("click", function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            var mark = $(this).attr("mark");
            var action = $(this).attr("action");
            var name = $(this).attr("value");
            var userInfo = $(this).data("userInfo");
            me.requestUrl = $(this).attr("requestUrl");
            me._mark = mark;
            me._action = action;
            me._name = name;
            me._userInfo = userInfo;
            me.buttonClick();
        });
        if ($(".tj_button2 p input").length <= 0) {
            $(".tj_button2").remove();
            $("#scrol_").css({
                height: height - 44 + "px"
            });
            Yscroll.refresh();
        }
        if ($(".tj_button2 p input").length <= 2) {
            $(".tj_button2 p input").css({
                width: "40%"
            });
        }
        if ($(".tj_button2 p input").length === 3) {
            $(".tj_button2 p input").css({
                width: "26.1%"
            });
        }
        if ($(".tj_button2 p input").length === 4) {
            $(".tj_button2 p input").css({
                width: "20%"
            });
        }
    };
    ;//操作按钮 点击逻辑
    dongtai.prototype.buttonClick = function () {
        var me = this;
        var name = me._name;
        var mark = me._mark;
        var userInfo = me._userInfo;
        var flag = false;
        if (name.indexOf("办结") > -1 || name.indexOf("完结") > -1) {
        ;
            navigator.notification.confirm('您确定要' + name + '此文件么？', showConfirm, 'OA', ['取消', '确定']);
            function showConfirm(button) {
                if (button == 2) {
                    me.submit();
                }
            }
            return;
        }
        if (mark != "true" && mark != "false") {
            me.submit();
            return;
        }
        var d1 = this._config.body || d3.select("body");
        var select = d3.select("body").append("div").classed("select", true).style({
            width: "100%",
            height: "100%",
            background: "#fff",
            position: "absolute",
            left: "0px",
            top: "0px",
            "z-index": 9990,
            "over-follow": "hidden"
        });

        var dt_warp = select.append("div").classed("dt_warp", true);
        var head = dt_warp.append("div").classed("datong_header", true);
        head.append("h1").html(me._taskName);
        var back = head.append("div").classed("go_back", true);
        back.html("<i><img src =../../common/page/images/go_back_ico.png width =16 height=auto></i>返回");
        back.on(touch_s, function () {
            $(this).css("background-color", "#005ebf");
        });
        // 左上角返回按钮 动作
        back.on(touch_e, function () {
            $(this).css("background-color", "");

            setTimeout(function () {
                select.remove();
                // Android返回键动作更改
                Android.back = TempFunction.back1;
            }, 10);
        });
        var datong_con = dt_warp.append("div").classed("datong_con", true).style({
            height: (height - 44) + "px"

        });
        var dist = 122
        if (mark == "true") {
            var dist = 285
            var ps_con = datong_con.append("div").classed("ps_con", true);
            var tj_select = ps_con.append("div").classed("tj_select", true).style({
            });
            var tj_con = tj_select.append("div").classed("div_input div_input2", true);
            var label = tj_con.append("label");
            var commonLanguage = label.append("button").classed("commonLanguage", true).style({
            }).html("常用语句");
            commonLanguage.on(touch_e, function () {
                if (Flag)
                    return;
                Flag = true;
                setTimeout(function () {
                    Flag = false;
                }, 500);
                me.Language();
            });
            var textarea = $("<textarea></textarea>").attr("rows", "5");
            $(tj_con.node()).append(textarea);
        }
        if (userInfo.length || objectJudge(userInfo)) {
            datong_con.append("div").classed("report_title", true).html("选择收件人").style({
                "text-align": "center"
            });
            var list = datong_con.append("div").classed("list", true).style({
                width: "100%",
                height: (height - dist) + "px",
                "over-follow": "hidden",
                "margin": "0 auto"
            }).attr("id", "list");
            var table = list.append("div").style({
                display: "table",
                width: "100%"
            }).attr("cellpadding", "0").attr("cellspacing", "0");
            listTable(userInfo, table);
            //下一位收件人列表
            function listTable(menber, table) {
                for (var party in menber) {
                    if (!menber[party].length)
                        continue;
                    var tr = table.append("div").classed("sjt_tit", true).html(party);
                    ;
                    var tr1 = table.append("div").classed("sjr_name", true);
                    var ul = tr1.append("ul");
                    for (var j = 0; j < menber[party].length; j++) {
                        var li = ul.append("li").attr("action", menber[party][j]["action"])
                            .attr("roleCode", menber[party][j]['roleCode']).attr("userName", menber[party][j]["userName"]);
                        li.html("<i class= choose_ico></i>" + menber[party][j]["userName"]);


                        li.on("click", function () {
                            if (Flag)
                                return;
                            Flag = true;
                            setTimeout(function () {
                                Flag = false;
                            }, 500);
                            $("li").removeClass("sel1");
                            $(this).addClass("sel1");
                            me._roleCode = $(this).attr("roleCode");
                            me._roleName = $(this).attr("userName");
                            d3.selectAll("i").classed("choosed_ico", false).classed("choose_ico", true);
                            d3.select(this).select("i").classed("choosed_ico", true).classed("choose_ico", false);
                        });
                    }


                }
            }

// 添加列表滑动效果
            Myscroll = new iScroll("list", {hScrollbar: false, vScrollbar: false});

        }
        var tj_button = datong_con.append("div").classed("tj_button2", true).classed("qb_btn_bg", true).style({
            bottom: "0px"
        });
        var cancel = tj_button.append("input").classed("btn_back", true).attr("type", "button")
            .attr("value", "取  消");
        var ensure = tj_button.append("input").classed("btn_agree", true).attr("type", "button")
            .attr("value", "确  认");
        ensure.on(touch_e, function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            console.log($("textarea").length)
            if (mark == "true" && !$("textarea").val().length) {
                Prompt("请输入意见", 1000);
                return;
            }
            if (userInfo.length || objectJudge(userInfo) && !me._roleCode) {
                Prompt("请选择收件人", 1000);
                return;
            }
            me.submit();
        });
        // 点击取消
        cancel.on(touch_e, function () {
            if (Flag)
                return;
            Flag = true;
            setTimeout(function () {
                Flag = false;
            }, 500);
            // 退回到详细页面
            setTimeout(function () {
                select.remove();
                // Android 返回键动作更改
                Android.back = TempFunction.back1;
            }, Transiacion);
        });
        // Android 返回键动作
        function back2() {
            $(".comList").remove();
            $(".mark").remove();
            setTimeout(function () {
                select.remove();
            }, 500);
            Android.back = TempFunction.back1;
        }

        Android.back = TempFunction.back2 = back2;
    }
    ;// 向后台提交操作结果
    dongtai.prototype.submit = function () {
        var me = this;
        var action = me._action;

        if (me._mark == "true" || me._mark == "false") {
            var value = $("textarea").val();
        } else {
            var value = me._mark;
        }
        var url = serverURL + "cmcp/phone/approvalInfo";
        var d1 = this._config.body || d3.select("body");
        var self = {
            approvalFlag: action,
            taskId: me._taskId,
            id: me._id,
            businessType: me._typeReal || me._businessType,
            requestUrl: me.requestUrl || null,
            type: me._type,
            roleCodes: me._roleCode,
            mark: value
        };
        console.log(self);
        PostCP(url, self, function (data) {
            window.plugins.getIntent.hide();
            console.log(data);
            if (!data) {
                Prompt("操作失败，请重新登录。", 1000);
                return;
            }
            if (data != "success") {
                Prompt("该文件已被处理！", 1000);
                return;
            }

            Prompt("操作成功！", 1000);
            // 成功后返回待办列表

            setTimeout(function () {
                $(".comList").remove();
                $(".mark").remove();
                d3.select(".select").remove();
                d3.selectAll("#scrol").remove();
                Android.back = TempFunction.back;
            }, Transiacion);
            window.localStorage.status = "true";

        }, function () {
            // 失败显示提示信息

            Prompt("操作失败，请重新登录。", 1000);
        })

    };
    // 动态类型转换
    dongtai.prototype.turnName = function (name) {
        var me = this;
        var Dicts = me.Dicts["dynamic_category"] || [];
        for (var i = 0; i < Dicts.length; i++) {
            if (Dicts[i]["code"] == name)
                return Dicts[i]["value"];
        }
        return "";
    };
    // 常用语列表
    dongtai.prototype.Language = function () {
        var me = this;
        var value = $("textarea").val();
        var url = serverURL + "cmcp/phone/doGetLanguages";
        var dat = me.languages;
        if (!dat["languages"] || !dat["languages"].length) {
            Alert("您还没有常用语句，请到后台维护您的常用语");
            return;
        }
        comList = dat["languages"] || comList;
        var List = d3.select("body").append("div").classed("comList", true);
        var head = List.append("div").classed("head", true).html("常用语列表");
        var con = List.append("div").classed("con", true).attr("id", "comList").style({
            "border-radius": "3px",
            background: "#ccdfee"
        });
        var ul = con.append("ul").style("overflow", "hidden").style({
            width: "80%",
            position: "absolute",
            left: "10%"
        });
        ul.append("li").style({
            height: "10px",
            "border-bottom": ".4px solod #838383"
        });
        for (var i = 0; i < comList.length; i++) {
            ul.append("li").html("<img src=../../common/page/images/mr.png > " + comList[i]);

        }
        ul.append("li").style({
            height: "10px",
            "border-bottom": ".4px solod #838383"
        });
        new iScroll("comList", {hScrollbar: false, vScrollbar: false});
        var html = "";
        $(".comList ul li").each(function () {
            $(this).on("click", function () {
                if (Flag)
                    return;
                Flag = true;
                setTimeout(function () {
                        Flag = false;
                    },
                    500
                )
                $(this).toggleClass("selec");
                var that = d3.select(this);
                if ($(this).hasClass("selec")) {
                    html += $(this).text() + " ";
                    that.select("img").attr("src", "../../common/page/images/xz.png");
                } else {
                    html = html.replace($(this).text() + " ", "");
                    that.select("img").attr("src", "../../common/page/images/mr.png");
                }
                $("textarea").val(value + html);

            });
        });
        var but = List.append("div").classed("but", true);
        var p = but.append("p").style({
            background: '#afbcca'
        });
        var but2 = p.append("button").style({
            width: "100px",
            height: "35px",
            background: "#d76856",
            color: "#ffe",
            "border-radius": "7px",
            "font-size": "18px",
            "margin": "10px"
        }).html("取 消");
        var but1 = p.append("button").style({  // 这里应该把样式写到 css 里
            width: "100px",
            height: "35px",
            border: '0px solid #70ab67',
            background: '#65d756',
            color: "#ffe",
            "border-radius": "7px",
            "font-size": "18px",
            "margin": "10px"
        }).html("确 认");

        but1.on("click", function () {
            Flag = true;
            List.remove();

            setTimeout(function () {
                Flag = false;
            }, 1000);

        });

        but2.on("click", function () {
            Flag = true;
            List.remove();

            $("textarea").val(value);
            setTimeout(function () {
                Flag = false;
            }, 1000);

        });


    }
    dongtai.prototype.openNew = function () {
        var me = this;
        var href = location.href;
        var len = href.lastIndexOf("views");
        var url = href.substr(0, len + 6) + "lcgz/lcgz.html?id=" + me._id + "&businessType=" + me._businessType + "&screenindex=" + me._screenindex;
        window.openViewC(url);
    };
    dongtai.prototype.getConfig = function (key) {
        if (this._config == null) {
            return null;
        } else {
            if (typeof (this._config[key]) != "undefined") {
                return this._config[key];
            } else {
                return null;
            }
        }
    };

})
()